package com.mt.mtbletools;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import com.mt.help.GlobalVariable;
import com.mt.help.SampleGattAttributes;
import com.mt.model.CharacterModel;
import com.mt.model.ServiceModel;
import com.mt.mtbletools.TalkFragment.Msg;
import com.mt.mtbletools.R;
import com.mt.sdk.ble.MTBLEDevice;
import com.mt.sdk.ble.MTBLEManager;
import com.mt.sdk.ble.base.BLEBase;
import com.mt.sdk.ble.model.BLEBaseAction.Option;
import com.mt.sdk.ble.model.ErroCode;
import com.mt.sdk.ble.model.ReadCharactAction;
import com.mt.sdk.ble.model.ReadDescriptorAction;
import com.mt.sdk.ble.model.WriteCharactAction;
import com.mt.sdk.ble.model.WriteDescriptorAction;
import com.mt.sdk.tools.MTTools;

import android.app.ProgressDialog;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.widget.Toast;

public class BaseBleActivity extends FragmentActivity {
	private Handler handl = new Handler();
	private GlobalVariable mGlobalVariable;
	private MTBLEManager manger;
	private BLEBase mBle;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_backfragment);
		mGlobalVariable = GlobalVariable.getinstance();
		manger = mGlobalVariable.getBleManger();

		mBle = new BLEBase(getApplicationContext(), manger) {

			@Override
			protected void onBaseConnect(ErroCode errocode) {
				super.onBaseConnect(errocode);
				System.out.println("onBaseConnect->" + errocode.toString());
				if (errocode.getCode() == 0) {
					readAllCharactName();
					return;
				}
				if ((pd != null) && (pd.isShowing())) { // 连接失败的情况
					pd.dismiss();
				}
				Toast.makeText(BaseBleActivity.this, "连接失败->" + errocode.getMsg(), Toast.LENGTH_LONG).show();
			}

			@Override
			protected void reTryConnect(int lasttimes) {
				super.reTryConnect(lasttimes);
				if ((pd != null) && (pd.isShowing())) {
					pd.setTitle("正在尝试重试：" + lasttimes);
				}
			}

			@Override
			protected void onDisConnect(ErroCode errocode) {
				super.onDisConnect(errocode);
				Toast.makeText(getApplicationContext(), "断开连接", Toast.LENGTH_SHORT).show();
				if(talkfragment != null){
					talkfragment.setConnectStatues(mBle.isConnected());
				}
			}

			@Override
			protected void onManualDisConnect(ErroCode errocode) {
				super.onManualDisConnect(errocode);
			}

			@Override
			protected void onCharactChanged(BluetoothGattCharacteristic characteristic, byte[] datas) {
				super.onCharactChanged(characteristic, datas);
				Msg msg = new Msg(characteristic, Msg.DIR.RECIVE, datas, MTTools.convertBytearrayToString(datas));
				allMsg.add(msg);

				if (talkfragment == null) {
					return;
				}
				if (characteristic == workingCharact) {
					talkfragment.receiveSelfdata(msg);
				} else {
					talkfragment.reciveOtherdata(msg);
				}
			}

		};

		initFragment();

		getDefaultDatas();

		startConnect();
	}

	// 获取传送过来的数据
	private MTBLEDevice device;
	private int index;

	private void getDefaultDatas() {
		index = getIntent().getIntExtra(AdvertisementActivity.SELECTDEVICE, -1);
		if (index == -1) {
			finish();
			return;
		}
		if (mGlobalVariable.getDeviceList().size() == 0) {
			finish();
			return;
		}
		device = mGlobalVariable.getDeviceList().get(index);
	}

	// 连接
	private ProgressDialog pd;

	private void startConnect() {
		pd = ProgressDialog.show(BaseBleActivity.this, "wait", "正在连接", true, true, new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				mBle.disConnect();
			}
		});

		ErroCode result = mBle.connect(device.getDevice().getAddress(), 1, false);
		if (result.getCode() != 0) { // 连接失败
			return;
		}
	}

	// 读取所有名字
	private List<ServiceModel> grounps;
	private List<List<CharacterModel>> childs;
	private BluetoothGattDescriptor lastdescriptor; // 最后一个值

	private void readAllCharactName() {
		List<BluetoothGattService> services = mBle.getAllServices();
		String uuid;

		grounps = new ArrayList<ServiceModel>();
		childs = new ArrayList<List<CharacterModel>>();

		for (BluetoothGattService service : services) {
			uuid = service.getUuid().toString();
			
			// 添加一个一级目录
			ServiceModel servicemodel = new ServiceModel();
			servicemodel.setName(SampleGattAttributes.lookup(uuid, "unknow"));
			servicemodel.setService(service);
			
//			List<BluetoothGattCharacteristic> grounpCharacteristic = new ArrayList<BluetoothGattCharacteristic>();
			List<CharacterModel> charactmodellist = new ArrayList<CharacterModel>();

			List<BluetoothGattCharacteristic> gattCharacteristics = service.getCharacteristics();
			if (gattCharacteristics.size() == 0) {
				childs.add(charactmodellist);
				grounps.add(servicemodel);
				continue;
			}

//			// 添加一个一级目录
//			ServiceModel servicemodel = new ServiceModel();
//			servicemodel.setName(SampleGattAttributes.lookup(uuid, "unknow"));
//			servicemodel.setService(service);
//
//			List<BluetoothGattCharacteristic> grounpCharacteristic = new ArrayList<BluetoothGattCharacteristic>();
//			List<CharacterModel> charactmodellist = new ArrayList<CharacterModel>();

			for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
				final CharacterModel charactmodel = new CharacterModel();
				charactmodel.setCharact(gattCharacteristic);
				uuid = gattCharacteristic.getUuid().toString();
				final BluetoothGattDescriptor descriptor = gattCharacteristic
						.getDescriptor(UUID.fromString("00002901-0000-1000-8000-00805f9b34fb"));
				if (descriptor == null) {
					charactmodel.setName(SampleGattAttributes.lookup(uuid, "unknow"));
				} else {
					System.out.println("readDescriptor->" + uuid);
					lastdescriptor = descriptor;
					mBle.addNewAction(new ReadDescriptorAction(descriptor, new Option(500)) {

						@Override
						public void onSuccess() {
							super.onSuccess();
							byte[] char_name_tmp = descriptor.getValue();
							boolean char_name_flag = true;
							for (byte char_name_tmp_byte : char_name_tmp) {
								if ((char_name_tmp_byte < 33) || (char_name_tmp_byte > 126)) {
									char_name_flag = false;
								}
							}
							if (!char_name_flag) {
								charactmodel.setName("unknow");
							} else {
								charactmodel.setName(new String(descriptor.getValue()));
							}

							if (lastdescriptor == descriptor) { // 最后一个值读取完毕
								System.out.println("读取成功");
								if ((pd != null) && (pd.isShowing())) {
									pd.dismiss();
								}
								gotoBleServiceListFragment();
							}
						}

						@Override
						public void onFail(ErroCode erro) {
							super.onFail(erro);
							System.out.println("读取失败->" + erro.toString());
							if ((pd != null) && (pd.isShowing())) {
								pd.dismiss();
							}
							mBle.disConnect();
							// charactmodel.setName("unknow");
							// if (lastdescriptor == descriptor) { // 最后一个值读取完毕
							// System.out.println("读取失败->"+erro.toString());
							// if ((pd != null) && (pd.isShowing())) {
							// pd.dismiss();
							// }
							// }
						}
					});
				}

				if (0 != (gattCharacteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY)) {
					final BluetoothGattDescriptor setdescriptor = gattCharacteristic
							.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
					if (setdescriptor != null) {
						setdescriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
						lastdescriptor = setdescriptor;
						mBle.addNewAction(new WriteDescriptorAction(setdescriptor, new Option(1000)) {

							@Override
							public void onSuccess() {
								super.onSuccess();
								if (lastdescriptor == setdescriptor) { // 最后一个值读取完毕
									System.out.println("读取成功");
									if ((pd != null) && (pd.isShowing())) {
										pd.dismiss();
									}
									gotoBleServiceListFragment();
								}
							}

							@Override
							public void onFail(ErroCode erro) {
								super.onFail(erro);
								System.out.println("读取失败->" + erro.toString());
								if ((pd != null) && (pd.isShowing())) {
									pd.dismiss();
								}
								mBle.disConnect();
							}

							@Override
							public void onCancel() {
								super.onCancel();
							}

						});
					} else {
						System.out.println("PROPERTY_NOTIFY null");
					}

				} else if (0 != (gattCharacteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_INDICATE)) {
					final BluetoothGattDescriptor setdescriptor = gattCharacteristic
							.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
					if (setdescriptor != null) {
						setdescriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
						lastdescriptor = setdescriptor;
						mBle.addNewAction(new WriteDescriptorAction(setdescriptor, new Option(1000)) {

							@Override
							public void onSuccess() {
								super.onSuccess();
								if (lastdescriptor == setdescriptor) { // 最后一个值读取完毕
									System.out.println("读取成功");
									if ((pd != null) && (pd.isShowing())) {
										pd.dismiss();
									}
									gotoBleServiceListFragment();
								}
							}

							@Override
							public void onFail(ErroCode erro) {
								super.onFail(erro);
								System.out.println("读取失败->" + erro.toString());
								if ((pd != null) && (pd.isShowing())) {
									pd.dismiss();
								}
								mBle.disConnect();
							}

							@Override
							public void onCancel() {
								super.onCancel();
							}

						});
					} else {
						System.out.println("PROPERTY_INDICATE = null");
					}

				}

				charactmodellist.add(charactmodel);
			}
			childs.add(charactmodellist);
			grounps.add(servicemodel);
		}

	}

	// 初始化fragment
	private FragmentManager fm;
	private BaseBleServiceListFragment serviceslistFragment;
	private TalkFragment talkfragment;
	private BluetoothGattCharacteristic workingCharact;
	private List<Msg> allMsg = new ArrayList<TalkFragment.Msg>();

	private void initFragment() {
		fm = getSupportFragmentManager();
		serviceslistFragment = new BaseBleServiceListFragment() {

			@Override
			protected void onClick(int grounpid, int childid) {
				super.onClick(grounpid, childid);
				System.out.println("servies->"+mBle.getAllServices().size());
				System.out.println("grounpid->"+grounpid+" childid->"+childid);
				BluetoothGattService service = mBle.getAllServices().get(grounpid);
				System.out.println("service size->"+service.getCharacteristics().size());
				workingCharact = mBle.getAllServices().get(grounpid).getCharacteristics().get(childid);
				System.out.println("mBle.getAllServices().get(grounpid).getCharacteristics().get(childid)");
				gotoTalkFragment();
			}

			@Override
			protected void onEnableClick(BluetoothGattCharacteristic charact, boolean enable) {
				super.onEnableClick(charact, enable);

				if (enable) {
					mBle.addListCharact(charact);
				} else {
					mBle.removeListCharact(charact);
				}
			}

		};

		talkfragment = new TalkFragment(getApplicationContext()) {
			@Override
			protected void onSendMsg(Msg msg) {
				super.onSendMsg(msg);

				if (!mBle.isConnected()) {
					return;
				}

				msg.setCharact(workingCharact);
				allMsg.add(msg);

				mBle.addNewAction(new WriteCharactAction(msg.getCharact(), msg.getRealmsg(), new Option(1000)));
			}

			@Override
			protected void onRead() {
				super.onRead();
				mBle.addNewAction(new ReadCharactAction(workingCharact, new Option(1000)) {

					@Override
					public void onReadDatas(BluetoothGattCharacteristic characteristic, byte[] datas) {
						super.onReadDatas(characteristic, datas);

						Msg msg = new Msg(workingCharact, Msg.DIR.RECIVE, datas, "");
						allMsg.add(msg);

						talkfragment.receiveSelfdata(msg);
					}
				});
			}

		};

	}

	private int fragment_index = 0;

	// 跳转到服务列表
	private void gotoBleServiceListFragment() {
		serviceslistFragment.setDatas(grounps, childs);
		FragmentTransaction ft = fm.beginTransaction();
		ft.replace(R.id.page_continer, serviceslistFragment);
		ft.commit();
	}

	// 跳转到对话列表
	private void gotoTalkFragment() {

		List<Msg> msglist = new ArrayList<Msg>();

		for (Msg msg : allMsg) {
			if (msg.getCharact() == workingCharact) {
				msglist.add(msg);
			}
		}

		FragmentTransaction ft = fm.beginTransaction();
		ft.replace(R.id.page_continer, talkfragment);
		ft.addToBackStack(null);
		ft.commit();

		talkfragment.setProperty(
				(0 != (workingCharact.getProperties() & BluetoothGattCharacteristic.PROPERTY_WRITE))
						|| (0 != (workingCharact.getProperties()
								& BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE)),
				(0 != (workingCharact.getProperties() & BluetoothGattCharacteristic.PROPERTY_READ)));
		talkfragment.setHisDatas(msglist);
		talkfragment.setConnectStatues(mBle.isConnected());
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(mBle.isConnected()){
			mBle.disConnect();
		}
	}
}
